package com.xzy.scheduling.service.e;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 说明：
 * <p>1.使用默认的SingleThreadScheduledExecutor处理定时任务</p>
 * <p>2.将定时任务的执行交给自定义的线程池</p>
 * <p>3.控制定时任务的并发：定时任务的处理时间很长 OR 定时任务的触发间隔很短，导致上一个定时任务还没处理完，下一个定时任务又开始执行</p>
 *
 * @author xzy
 * @date 2022/12/8  21:28
 */
@Slf4j
@Service
public class MyScheduledService {

    private final ReentrantLock lock = new ReentrantLock();
    private final ExecutorService executorService = Executors.newFixedThreadPool(5);


    @Scheduled(cron = "0/1 * * * * ? ")
    public void task() {
        log.info("Task：start");
        executorService.execute(() -> {
            if (!lock.tryLock()) {
                log.info("加锁失败，终止执行");
                return;
            }

            log.info("加锁成功，开始执行");
            try {
                aLongTimeTask(10000);
            } finally {
                lock.unlock();
            }

            log.info("Task：end\n");
        });
    }

    private void aLongTimeTask(long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
